# coding: utf-8

from __future__ import absolute_import, division, print_function, unicode_literals

import os.path

from apitest.engine.client.http import HttpxClient
from apitest.engine.config import Config
from apitest.engine.const.model import PSMAuth, PSMConfFromYaml
from apitest.engine.env import EnvModel, run_env
from apitest.engine.logging import logger


class BaseService:

    def __init__(self, psm, auth: PSMAuth = None, Env: EnvModel = None, **kwargs):
        self.env = run_env
        if Env:
            self.env.set_env(Env)
            self.env.env_updater()

        self.psm = psm
        self.psm_str = self.psm.replace(".", "_")
        self._host()
        if auth:
            self.auth = auth
        else:
            self.auth = PSMAuth()
        if not self.auth.phone:
            self.auth.phone = self.conf.phone
        self.auth.psm = self.psm
        self.client = HttpxClient(base_url=self.host, **kwargs).client
        self._cookie_lib()

    def _host(self):
        try:
            cf = Config("config.yaml")
            conf = cf.get_conf(self.psm, self.env.region.value)
        except KeyError:
            cf = Config("config.yaml", repo_path=os.path.dirname(os.path.dirname(__file__)))
            conf = cf.get_conf(self.psm, self.env.region.value)

        self.conf = PSMConfFromYaml(**conf)
        self.host = self.conf.Host.all
        # 支持多机房host配置
        if self.env.idc is not None:
            self.host = getattr(self.conf.Host, self.env.idc.value, self.host)

    def _cookie_lib(self):
        if self.conf.auth is None or (self.conf.auth.header is None and self.conf.auth.cookie is None):
            logger.warning("not found auth, please check psm config.")
            return
        if self.conf.auth.header is not None:
            for k, val in self.conf.auth.header.dict().items():
                if getattr(self.auth.token, k, None) is None and (val is not None or val != ""):
                    setattr(self.auth.token, k, val)
                self.client.headers.update({k: getattr(self.auth.token, k, "")})

        if self.conf.auth.cookie is not None:
            for k, val in self.conf.auth.cookie.dict().items():
                if getattr(self.auth.cookie, k, None) is None and (val is not None or val != ""):
                    setattr(self.auth.cookie, k, val)
                self.client.cookies.set(k, getattr(self.auth.cookie, k, ""), domain=self.host[self.host.find(".") + 1:])

    # 封装了常用中台session和四轮引擎session，其他鉴权方式需自行实现
    def session_lib(self, session):
        self.auth.cookie.sessionid = session
        self._cookie_lib()

    def fwe_session_lib(self, session):
        self.auth.cookie.fw_account_session_key = session
        self._cookie_lib()

    def pool_lib(self, token):
        self.auth.token.owner = token
        self._cookie_lib()
